package struts.action;

import java.util.List;

import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cart.CartItem;

import struts.actionform.CheckoutForm;

import ejb.bl.CartBeanRemote;
import ejb.bl.MusicStoreBLRemote;

public class CheckoutAction extends Action {

	// Define EJB Session Bean
	private CartBeanRemote CartBean;
	private MusicStoreBLRemote MusicStoreBLBean;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();

		String userid = (String) session.getAttribute("UserID");
		if (userid == null) {
			return mapping.findForward("login");
		}

		InitialContext ic = null;
		if (session.getAttribute("sessionContext") == null) {
			ic = new InitialContext();
			session.setAttribute("sessionContext", ic);
		} else {
			ic = (InitialContext) session.getAttribute("sessionContext");
		}
		String forward2Page = "input";
		CartBean = (CartBeanRemote) session.getAttribute("CartBean");
		MusicStoreBLBean = (MusicStoreBLRemote) ic
				.lookup("java:global/IMusicStore/MusicStoreStalessBean");
		CheckoutForm objForm = (CheckoutForm) form;
		int Id = Integer.parseInt(userid);

		try {
			if (objForm.getUpdateAction().equals("update")) {
				if (objForm.getAction().equals("add")) {
					List<CartItem> cart = CartBean.getContents();
					if (MusicStoreBLBean.saveOrder(Id, cart)) {
						CartBean.resetCart();
						forward2Page = "success";
					}
				}
			} else {
				request.setAttribute("cartItems", CartBean.getContents());
				request.setAttribute("account",
						MusicStoreBLBean.getCustomerById(Id));
			}

		} catch (Exception e) {
			forward2Page = "input";
			System.out.println("Errors==>" + e.getMessage());
		}

		// Display the registration form to the user
		return mapping.findForward(forward2Page);
	}
}
